package org.example;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CreateReceipt {
    public static JSONObject generateReceiptContent(JSONArray givenBarcodeAmount, JSONArray productList) {
        JSONObject receiptContect = new JSONObject();
        JSONArray productsArray = new JSONArray();
        float allProductTotal = 0;
        for(int i = 0; i < givenBarcodeAmount.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            JSONObject barcodeJson = (JSONObject) givenBarcodeAmount.get(i);
            String amount = (String) barcodeJson.get("amount");
            String barcodeInAmountList = (String) barcodeJson.get("barcode");
            for(int j = 0; j < productList.size(); j++) {
                float total = 0;
                JSONObject productJson = (JSONObject) productList.get(j);
                String barcodeInProductlist = (String) productJson.get("Barcode");
                if(barcodeInProductlist.equals(barcodeInAmountList)) {
                    String price = (String) productJson.get("Price");
                    String productName = (String) productJson.get("Name");
                    total = Float.valueOf(price) * Integer.parseInt(amount);
                    allProductTotal += total;
                    jsonObject.put("Name", productName);
                    jsonObject.put("Amount", amount);
                    jsonObject.put("Price", price);
                    jsonObject.put("Total", String.valueOf(total));
                    productsArray.add(jsonObject);
                }
            }
        }
        receiptContect.put("products", productsArray);
        receiptContect.put("totalPrice", String.valueOf(allProductTotal));
        return receiptContect;
    }
}
